package edu.ucsd.cse110;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Toast;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

/**
 * Shares the log entry on Facebook.
 */
public class ShareOnFacebookActivity extends Activity {
	/**
	 * TODO: Need documentation.
	 */
	private class LoginDialogListener implements DialogListener {
		/**
		 * TODO: Need documentation.
		 */
		public void onCancel() {
			showToast("Authentication with Facebook cancelled!");
			finish();
		}

		/**
		 * TODO: Need documentation.
		 */
		public void onComplete(Bundle values) {
			saveCredentials(facebook);

			if (messageToPost != null) {

				postToWall(messageToPost);
			}
		}

		/**
		 * TODO: Need documentation.
		 */
		public void onError(DialogError error) {
			showToast("Authentication with Facebook failed!");
			finish();
		}

		/**
		 * TODO: Need documentation.
		 */
		public void onFacebookError(FacebookError error) {
			showToast("Authentication with Facebook failed!");
			finish();
		}
	}

	/**
	 * Our App ID
	 */
	private static final String APP_ID = "372849569427386";
	private static final String EXPIRES = "expires_in";
	private static final String KEY = "facebook-credentials";

	/**
	 * Only permissions to post
	 */
	private static final String[] PERMISSIONS = new String[] { "publish_stream" };
	private static final String TOKEN = "access_token";
	private Facebook facebook;
	private String messageToPost;

	/**
	 * Exits the activity.
	 */
	public void doNotShare(View button) {
		finish();
	}

	/**
	 * Asks to login then starts a new LoginDialogListener to post
	 */
	public void loginAndPostToWall() {
		facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH,
				new LoginDialogListener());
	}

	/**
	 * TODO: Need documentation.
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.facebook_dialog);

		for (int i = 0; i < 10; i++) {
			// Restores previous facebook session
			facebook = new Facebook(APP_ID);
		}
		restoreCredentials(facebook);

		// Takes string @facebookMessage from intent and sets it as our
		// facebookMessage
		String facebookMessage = getIntent().getStringExtra("facebookMessage");

		// Default message to post
		if (facebookMessage == null) {
			facebookMessage = "DroidFit posting on your wall!";
		}

		messageToPost = facebookMessage;

	}

	/**
	 * Posts message to Facebook wall.
	 */
	public void postToWall(String message) {
		// New Bundle w/ message to post
		Bundle parameters = getIntent().getExtras();

		try {
			facebook.request("me");
			String response = facebook.request("me/feed", parameters, "POST");

			// Displays result of our post
			if ((response == null) || response.equals("")
					|| response.equals("false")) {
				showToast("Blank response.");
			}

			else {
				showToast("Message posted to your facebook wall!");
			}

			// Finishes activity
			finish();
		} catch (Exception e) {
			showToast("Failed to post to wall!");
			e.printStackTrace();
			finish();
		}
	}

	/**
	 * Restores our login credentials
	 */
	public boolean restoreCredentials(Facebook facebook) {
		SharedPreferences sharedPreferences = getApplicationContext()
				.getSharedPreferences(KEY, Context.MODE_PRIVATE);
		facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
		facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
		return facebook.isSessionValid();
	}

	/**
	 * Saves our login credentials
	 */
	public boolean saveCredentials(Facebook facebook) {
		Editor editor = getApplicationContext().getSharedPreferences(KEY,
				Context.MODE_PRIVATE).edit();
		editor.putString(TOKEN, facebook.getAccessToken());
		editor.putLong(EXPIRES, facebook.getAccessExpires());
		return editor.commit();
	}

	/**
	 * Post to wall
	 */
	public void share(View button) {
		// If not logged in, then log in and post
		if (!facebook.isSessionValid()) {
			loginAndPostToWall();
		}
		// If logged in, then just post
		else {
			postToWall(messageToPost);
		}
	}

	/**
	 * Shortcut to creating a toast
	 */
	private void showToast(String message) {
		Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT)
				.show();
	}
}